using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;

namespace LiveLinq.Internal
{
	sealed class ConcatQueryResult<T> : ObservableCollectionQueryResultBase<T>
	{
		readonly IEnumerable<T> _secondSource;
		readonly INotifyCollectionChanged _secondSourceNotifiable;

		public ConcatQueryResult(IEnumerable<T> first, IEnumerable<T> secondSource)
			: base(first)
		{
			_secondSource = secondSource;
			_secondSourceNotifiable = secondSource as INotifyCollectionChanged ?? NullNotifyCollectionChanged.Instance;
			_secondSourceNotifiable.CollectionChanged += Source_CollectionChanged;
			OnSourceReset();
		}

		protected override void OnSourceReset()
		{
			foreach (var item in _attached)
			{
				DetachItem(item);
			}
			_attached.Clear();
			Items.Clear();
			foreach (var item in _source)
			{
				AttachItem(item);
				Items.Add(item);
			}
			foreach (var item in _secondSource)
			{
				AttachItem(item);
				Items.Add(item);
			}
			OnPropertyChanged(_pcCount);
			OnPropertyChanged(_pcIndexer);
			OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
		}

		protected override void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			OnSourceReset();
		}

	}
}